package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.FriendLinkManager;
import com.anne.fish.model.FriendLink;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class FriendLinkAction extends BaseAction implements Preparable {
    private FriendLinkManager friendLinkManager;
    private List friendLinks;
    private FriendLink friendLink;
    private Long id;
    private String query;

    public void setFriendLinkManager(FriendLinkManager friendLinkManager) {
        this.friendLinkManager = friendLinkManager;
    }

    public List getFriendLinks() {
        return friendLinks;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String friendLinkId = getRequest().getParameter("friendLink.id");
            if (friendLinkId != null && !friendLinkId.equals("")) {
                friendLink = friendLinkManager.get(new Long(friendLinkId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        friendLinks = friendLinkManager.search(query, FriendLink.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public FriendLink getFriendLink() {
        return friendLink;
    }

    public void setFriendLink(FriendLink friendLink) {
        this.friendLink = friendLink;
    }

    public String delete() {
        friendLinkManager.remove(friendLink.getId());
        saveMessage(getText("friendLink.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            friendLink = friendLinkManager.get(id);
        } else {
            friendLink = new FriendLink();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (friendLink.getId() == null);

        friendLinkManager.save(friendLink);

        String key = (isNew) ? "friendLink.added" : "friendLink.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}